<template>
  <view class="template-home tn-safe-area-inset-bottom">
    <!-- 方式1 start-->
    <view class="tn-flex home-fixed" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
      <!--      蓝牙已断开-->
      <view class="tn-flex-1 tn-padding-sm tn-margin-xs tn-radius" @click="test()">
        <view class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center">
          <view class="icon1__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-bg-white tn-color-black">
            <view class="tn-icon-bluetooth" :style="{color: bluetoothData.color}"></view>
          </view>
          <view class="tn-color-gray--dark tn-text-center">
            <text class="tn-text-ellipsis">{{bluetoothData.text}}</text>
          </view>
        </view>
      </view>
      <!--      搜索蓝牙-->
      <view class="tn-flex-1 tn-padding-sm tn-margin-xs tn-radius" @click="clickSearchOrBreak">
        <view class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center">
          <view class="icon1__item--icon tn-flex tn-flex-row-center tn-flex-col-center tn-bg-white tn-color-black">
            <view class="tn-icon-circle-fill" :style="{color: searchOrBreak.color}"></view>
          </view>
          <view class="tn-color-gray--dark tn-text-center">
            <text class="tn-text-ellipsis">{{searchOrBreak.text}}</text>
          </view>
        </view>
      </view>
    </view>
    <!--    蓝牙列表-->
    <view class="tn-margin-top-sm" :style="{paddingTop: vuex_custom_bar_height + 100 +'px'}">
      <view>
        <view class="tn-flex tn-flex-col-center" style="margin: 50rpx 30rpx;" v-for="(item, index) in baseList" :key="index" @click="connectBluetooth(item)">
          <view class="tn-padding-left-sm">
            <view class="tn-flex tn-flex-row-between tn-flex-col-between">
              <view class="justify-content-item">
                <text class="color-tnoa tn-text-lg tn-text-bold">{{item.name}} | RSSI:{{item.RSSI}}</text>
              </view>
            </view>
            <view class="tn-padding-top-xs">
              <text class="tn-color-gray">{{item.deviceId}}</text>
            </view>
          </view>
        </view>
        <!--        无数据时显示图片-->
        <view v-show="emptyShow" style="margin-top: 150px">
          <tn-empty icon="/static/image/network.jpg" text="无蓝牙设备！"></tn-empty>
        </view>
      </view>
    </view>

    <view class="tn-tabbar-height"></view>

    <!--    消息提示-->
    <tn-modal v-model="notifyData.show" title="温馨提醒!" width="60%" :content="notifyData.content"></tn-modal>
    <tn-tips ref="tips" position="center"></tn-tips>

    <!--    搜索蓝牙设备-->

    <!-- 压屏窗-->
    <tn-landscape
        :show="connectShow"
        :closeBtn=false
        :mask=true
        :maskCloseable=false
    >
      <tn-loading :show="connectShow" :size="320"></tn-loading>
    </tn-landscape>

  </view>
</template>

<script>
export default {
  name: 'Home',
  data() {
    return {
      connectShow: false, //加载圈显示隐藏状态(搜索蓝牙、连接蓝牙)
      bluetoothData: {
        color: '#838383', //#31E749 连接
        text: '蓝牙已断开'
      },
      searchOrBreak: {
        type: 'search',
        text: '搜索',
        color: '#82B2FF',
      },
      baseList: [], //蓝牙设备列表
      discoveryStarted: false, //搜索设备是否开启
      connectBluetoothName: '', //当前要连接的蓝牙名
      deviceId: '', //当前连接的设备id
      serviceId: '', //服务id
      characteristicId: '', //特征id
      bluetoothIndex: [], //蓝牙设备id
      loadingText: '搜索设备中...',
      loadingShow: false, //顶部"搜索设备中"展示
      notifyData: {
        content: '',
        show: false,
      },
      connecting: false, //连接状态
      emptyShow: true,
    }
  },
  created() {
    this.openBluetoothAdapter()
  },
  methods: {
    //连接蓝牙
    connectBluetooth(item) {
      console.log(this.searchOrBreak.type)
      if (this.searchOrBreak.type === 'search') {
        this.connectShow = true
        this.connectBluetoothName = item.name
        this.createBLEConnection(item.deviceId)
        let $this = this
        setTimeout(function() {
          $this.connectShow = false
        }, 1500);
      }
    },
    clickSearchOrBreak() {
      console.log(this.searchOrBreak.type)
      if (this.searchOrBreak.type === 'break') {
        //执行断开蓝牙
        this.closeBLEConnect(this.deviceId)
        this.bluetoothData.color = '#838383'
        this.bluetoothData.text = '蓝牙已断开'
        this.searchOrBreak.type = 'search'
        this.searchOrBreak.text = '搜索'
        this.searchOrBreak.color = '#82B2FF'
      } else {
        //执行搜索蓝牙
        this.startBluetoothDevicesDiscovery()
        //定时关闭搜索设备
        setTimeout(() => {
          this.stopBluetoothDevicesDiscovery();
          this.loadingShow = false
        },10 * 1000);
      }
    },
    //初始化蓝牙模块
    openBluetoothAdapter() {
      uni.openBluetoothAdapter({
        success: () => {
          this.loadingText = '搜索设备中...'
          this.loadingShow = true
          setTimeout(() => {
            //每次扫码清空设备列表，不然会导致重复
            this.baseList = []
            this.bluetoothIndex = []
            //尝试搜素
            this.startBluetoothDevicesDiscovery();//搜索蓝牙设备
          },100);
          //定时关闭搜索设备
          setTimeout(() => {
            this.stopBluetoothDevicesDiscovery();
            this.loadingShow = false
          },10 * 1000);
        },
        fail: (res) => {
          //如果蓝牙未打开提示用户打开蓝牙
          this.notifyData.content = '请打开手机蓝牙!'
          this.notifyData.show = true
          if (res.errCode === 10001) {
            //监听蓝牙适配器状态变化事件
            uni.onBluetoothAdapterStateChange(function(res) {
              if (res.available) {
                //蓝牙打开成功，开始扫描
                this.startBluetoothDevicesDiscovery()
              }
            })
          }
        }
      })
    },
    //搜索附近的蓝牙外围设备
    startBluetoothDevicesDiscovery() {
      console.log('执行搜索蓝牙')
      console.log(this.discoveryStarted)
      if (this.discoveryStarted) {
        return;
      }
      this.discoveryStarted = true;
      //开始搜寻附近的蓝牙外围设备
      this.emptyShow = false
      console.log('开始搜寻附近的蓝牙外围设备')
      uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: () => {
          //监听寻找到新设备的事件
          this.baseList = []
          this.bluetoothIndex = []
          this.onBluetoothDeviceFound()
        },
        fail: () => {
          //搜索失败，返回提示
          this.discoveryStarted = false
          this.notifyData.content = '请检查蓝牙状态!'
          this.notifyData.show = true
        }
      })
    },
    //监听寻找到新设备
    onBluetoothDeviceFound() {
      let that =this;
      //监听寻找到新设备的事件
      uni.onBluetoothDeviceFound(function(res) {
        res.devices.forEach(device => {
          //name:蓝牙设备名称 localName:当前蓝牙设备的广播数据段中的 LocalName 数据段
          if (!device.name && !device.localName) {
            return;
          }
          //添加蓝牙设备列表
          let oneBluetooth = {
            deviceId: device.deviceId,
            name: device.name,
            RSSI:device.RSSI,
            localName:device.localName
          }
          //判断是否存在
          if(that.bluetoothIndex.indexOf(device.deviceId) === -1) {
            that.baseList.push(oneBluetooth);
            that.bluetoothIndex.push(device.deviceId);
          }
        })
      })
    },
    //创建连接蓝牙事件
    createBLEConnection(deviceId) {
      let that = this;
      //1）判断设备是否处于连接状态
      if(that.connecting) {
        //设备已连接
        this.$refs.tips.show({msg: '设备已连接!', backgroundColor: '#E83A30', fontColor: '#FFFFFF', duration: 1500})
      } else {
        //2）创建连接
        this.loadingText = '设备连接中...'
        this.loadingShow = true
        uni.createBLEConnection({
          deviceId:deviceId,
          success: () => {
            that.deviceId = deviceId;
            //不延迟造成获取不到服务！！！！，我走过的坑！！！
            setTimeout(function() {
              //获取设备的蓝牙服务
              that.getBLEDeviceServices(deviceId);
              //关闭等待提示
              setTimeout(function () {
                that.loadingShow = false
              }, 100)
            }, 1000)
          },
        });
        //3）设置MTU，否则传输报文不全，默认是23bytes，但是蓝牙本身是需要3bytes，故而只能传输20bytes
        setTimeout(()=>{
          uni.setBLEMTU({deviceId:deviceId, mtu:255});
        },1000);
        //4）关闭搜索
        this.stopBluetoothDevicesDiscovery();
      }
    },
    //获取蓝牙设备的所有服务
    getBLEDeviceServices(deviceId) {
      //获取蓝牙设备所有服务(service)
      uni.getBLEDeviceServices({
        deviceId,
        success: (res) => {
          if (res.services[1]) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[1].uuid);
          } else {
            this.connectShow = false
          }
          // for (let i = 0; i < res.services.length; i++) {
          //   if (res.services[i].isPrimary) {
          //     console.log('uuid' + res.services[i].uuid)
          //     this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
          //     return;
          //   }
          // }
        }
      });
    },
    //获取蓝牙设备某个服务中所有特征值
    getBLEDeviceCharacteristics(deviceId, serviceId) {
      //获取蓝牙设备某个服务中所有特征值(characteristic)
      uni.getBLEDeviceCharacteristics({
        deviceId,
        serviceId,
        success: (res) => {
          for (let i = 0; i < res.characteristics.length; i++) {
            let item = res.characteristics[i]
            //读取低功耗蓝牙设备的特征值的二进制数据值。1
            uni.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
            if (item.properties.write) {
              this.deviceId = deviceId;
              this.serviceId = serviceId;
              this.characteristicId = item.uuid;
              //写入请求数据
              uni.setStorageSync('ble_deviceId', deviceId);
              uni.setStorageSync('ble_serviceId', serviceId);
              uni.setStorageSync('ble_characteristicId', this.characteristicId);
              this.bluetoothData.color = '#31E749'
              this.bluetoothData.text = this.connectBluetoothName
              this.searchOrBreak.type = 'break'
              this.searchOrBreak.text = '断开'
              this.searchOrBreak.color = '#E83A30'
            }
            //启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
            uni.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
              success()
              {
                uni.onBLECharacteristicValueChange(characteristic => {
                  //将字节转换成16进制字符串
                  let data = this.ab2hex(characteristic.value)
                  console.log(data)
                  //将16进制转成字符串
                  // let newdataStr = Buffer.from(data,'hex');//先把数据存在buf里面
                  // that.btvalue=newdataStr.toString("utf-8");//使用toString函数就能转换成字符串
                  //设备返回SN
                  // that.SN=newdataStr.toString("utf-8");
                  //根据返回的数据处理设备类型和显示的输入区域-----------------
                  // that.getEquType(that.SN);
                });
              }
            });
          }
        },
      })
    },
    //关闭搜索
    stopBluetoothDevicesDiscovery() {
      //关闭搜索
      let $this = this
      uni.stopBluetoothDevicesDiscovery({
        success() {
          $this.discoveryStarted = false;
          console.log('搜索结束')
        }
      })
    },
    //断开蓝牙设备连接
    closeBLEConnect(deviceId) {
      uni.closeBLEConnection({
        deviceId,
        success:res => {
          this.deviceId = this.serviceId = this.characteristicId = "";
          uni.removeStorageSync('ble_deviceId');
          // this.baseList = []
          // this.bluetoothIndex = []
        },
      })
    },
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
          }
      )
      return hexArr.join('')
    },
    test() {
      console.log(111)
    },
  }
}
</script>

<style lang="scss" scoped>
.template-home{
  max-height: 100vh;
}

/* 自定义导航栏内容 start */
.custom-nav {
  height: 100%;

  &__back {
    margin: auto 5rpx;
    font-size: 45rpx;
    margin-right: 10rpx;
    margin-left: 30rpx;
    flex-basis: 5%;
  }
}
/* 自定义导航栏内容 end */

/* 新增OA色系，自行调用，或者拿色值去用，多种方式*/
.oa-black{
  color: #1D2541;
}
.oa-blue{
  color: #4B98FE;
}
.oa-orangeyellow{
  color: #FFAC00;
}
.oa-green{
  color: #00D05E;
}
.oa-orange{
  color: #FE871B;
}
.oa-cyan{
  color: #00C8B0;
}
.oa-indigo{
  color: #00B9FE;
}
.oa-orangered{
  color: #FB6A67;
}
.oa-purple{
  color: #957BFE;
}

/* 底部安全边距 start*/
.tn-tabbar-height {
  min-height: 120rpx;
  height: calc(140rpx + env(safe-area-inset-bottom));
  height: calc(140rpx + constant(safe-area-inset-bottom));
}


// 四个角渐变底色
.home-fixed{
  position: fixed;
  background: linear-gradient(90deg, #DBF2FE, #FFE1E1);
  top: 0;
  width: 100%;
  transition: all 0.25s ease-out;
  z-index: 100;
}
.home-fixed:before{
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  mask-image: linear-gradient(to bottom, transparent, black);
  background: linear-gradient(90deg, #FFFFFF, #FFFFFF);

}

/* OA黑色*/
.color-tnoa{
  color: #1D2541;
}

/* 页面阴影 start*/
.oa-shadow {
  border-radius: 15rpx;
  box-shadow: 0rpx 0rpx 50rpx 0rpx rgba(0, 0, 0, 0.07);
}




/* 图标容器1 start */
.icon1 {
  &__item {
    width: 30%;
    background-color: #FFFFFF;
    border-radius: 10rpx;
    padding: 30rpx;
    margin: 20rpx 10rpx;
    transform: scale(1);
    transition: transform 0.3s linear;
    transform-origin: center center;

    &--icon {
      width: 100rpx;
      height: 100rpx;
      font-size: 60rpx;
      border-radius: 50%;
      margin-bottom: 18rpx;
      position: relative;
      z-index: 1;

      &::after {
        content: " ";
        position: absolute;
        z-index: -1;
        width: 100%;
        height: 100%;
        left: 0;
        bottom: 0;
        border-radius: inherit;
        opacity: 1;
        transform: scale(1, 1);
        background-size: 100% 100%;
        background-image: url(https://resource.tuniaokj.com/images/cool_bg_image/icon_bg5.png);
      }
    }
  }
}

/* 图标容器15 start */
.icon15 {
  &__item {
    width: 30%;
    background-color: #FFFFFF;
    padding: 30rpx;
    margin: 20rpx 10rpx;
    transform: scale(1);
    transition: transform 0.3s linear;
    transform-origin: center center;

    &--icon {
      width: 90rpx;
      height: 90rpx;
      font-size: 60rpx;
      border-radius: 50%;
      position: relative;
      z-index: 1;

      &::after {
        content: " ";
        position: absolute;
        z-index: -1;
        width: 100%;
        height: 100%;
        left: 0;
        bottom: 0;
        border-radius: inherit;
        opacity: 1;
        transform: scale(1, 1);
        background-size: 100% 100%;


      }
    }
  }
}
/* 用户头像 start */
.logo-image {
  width: 90rpx;
  height: 90rpx;
  position: relative;
}
.logo-pic {
  background-size: cover;
  background-repeat: no-repeat;
  // background-attachment:fixed;
  background-position: center;
  // border: 1rpx solid rgba(255,255,255,0.05);
  // box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
  border-radius: 50%;
  overflow: hidden;
  // background-color: #FFFFFF;
}
</style>
